package by.euanpa.android.grodnobusstop.content.provider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import by.euanpa.android.grodnobusstop.content.db.DbHelper;

public class BusStopContentProvider extends ContentProvider{

	private DbHelper dbHelper;
	
	@Override
	public boolean onCreate() {
		dbHelper = new DbHelper(getContext());
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		Cursor cursor = dbHelper.getReadableDatabase().query(getType(uri), projection, selection, selectionArgs, null, null, sortOrder);
		return cursor;
	}
	
	@Override
	public Uri insert(Uri uri, ContentValues values) {
		SQLiteDatabase writableDatabase = dbHelper.getWritableDatabase();
		long insertCount = writableDatabase.insert(getType(uri), null, values);
		Uri workUri = ContentUris.withAppendedId(uri, insertCount);
		getContext().getContentResolver().notifyChange(workUri, null);
		return workUri;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		return 0;
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		SQLiteDatabase writableDatabase = dbHelper.getWritableDatabase();
		int delete = writableDatabase.delete(getType(uri), selection, selectionArgs);
		return delete;
	}
	
	@Override
	public String getType(Uri uri) {
		return uri.getLastPathSegment();
	}
}